﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using MyBlog.Common;
using MyBlog.Model;
using System.Web.Mvc;

namespace MyBlog
{
    public class UserSession
    {
        public const string SUPERADMIN = "superadmin";

        /// <summary>
        /// 保存用户会话信息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="isRemember"></param>
        public static void SaveSession(AccountModel user, bool? isRemember)
        {
            if (null == user)
            {
                return;
            }
            user.Account = user.Account.Trim();
            if (isRemember.HasValue && isRemember.Value)
            {
                var cookie = CookieHelper.GetCookie("userinfo");
                if (null == cookie)
                {
                    cookie = new HttpCookie("userinfo");
                    cookie.Values.Add("account", user.Account);
                    cookie.Values.Add("password", user.Password);
                    cookie.Expires = DateTime.Now.AddDays(365);
                    CookieHelper.AddCookie(cookie);
                }
                else
                {
                    if (!cookie.Values["account"].Equals(user.Account))
                    {
                        CookieHelper.SetCookie("userinfo", "account", user.Account);
                    }
                    if (!cookie.Values["password"].Equals(user.Password))
                    {
                        CookieHelper.SetCookie("userinfo", "password", user.Password);
                    }
                }
            }
            else
            {
                CookieHelper.RemoveCookie("userinfo");
            }

            //var ticket = new FormsAuthenticationTicket(user.Account,false,365);
            ////加密票据
            //string ticString = FormsAuthentication.Encrypt(ticket);
            ////输出到客户端
            //CookieHelper.AddCookie(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));
            FormsAuthentication.SetAuthCookie(user.Account, isRemember ?? false);
            HttpContext.Current.Session["loginUser"] = user;
        }

        /// <summary>
        /// 清除用户会话信息
        /// </summary>
        public static void ClearSession()
        {
            HttpContext.Current.Session.Clear();
            FormsAuthentication.SignOut();
        }

        /// <summary>
        /// 当前登录用户ID
        /// </summary>
        public static string AccountId
        {
            get
            {
                if (LoginUserInfo != null)
                {
                    return LoginUserInfo.Account.ToLower();
                }
                return null;
            }
        }

        /// <summary>
        /// 判断客户端是否已经登录用户
        /// </summary>
        public static bool IsLogin
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(AccountId) && HttpContext.Current.Request.IsAuthenticated)
                {
                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 用户会话信息
        /// </summary>
        public static AccountModel LoginUserInfo
        {
            get
            {
                if (HttpContext.Current.Session["loginUser"] != null)
                {
                    return HttpContext.Current.Session["loginUser"] as AccountModel;
                }
                else
                {
                    //var cookie=CookieHelper.GetCookie("userinfo");
                    //if (cookie!=null)
                    //{
                    //    var uname = cookie.Values["account"].ToString();
                    //    var pwd = cookie.Values["password"].ToString();
                    //    var account = XiaoBoKe.AccountService.Get(x => x.Account.ToLower() == uname && x.Password == pwd);
                    //    if (account!=null)
                    //    {
                    //        HttpContext.Current.Session["loginUser"] = account;
                    //        return account;
                    //    }
                    //}
                }
                return null;
            }
            set { }
        }

        /// <summary>
        /// 刷新会话信息
        /// </summary>
        public static void Refresh()
        {
            if (LoginUserInfo != null)
            {
                var user = XiaoBoKe.AccountService.Get(LoginUserInfo.Account);
                HttpContext.Current.Session["loginUser"] = user;
            }
        }

        /// <summary>
        /// 根据客户端相关信息与实际操作类型生成唯一的加密字符串
        /// </summary>
        /// <typeparam name="T">操作的对象类型</typeparam>
        /// <param name="opData">操作的数据</param>
        /// <returns></returns>
        public static string GetClientInfoMD5<T>(string opData)
        {
            string ip = GetClientIP();
            string browser = HttpContext.Current.Request.Browser.Browser;
            string browser_ver = HttpContext.Current.Request.Browser.Version;
            string clientinfo = DateTime.Now.Date.ToString("yyyy-MM-dd") + ip + browser + browser_ver + typeof(T).Name + opData;
            return clientinfo.MD5_16();
        }

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrWhiteSpace(ip))
            {
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrWhiteSpace(ip))
            {
                ip = HttpContext.Current.Request.UserHostAddress;
            }
            return ip;
        }

    }
}
